// 引入
import CryptoJS from 'crypto-js'

// 密钥
let AES_KEY:string = '' // 根据路由初始化
// 初始化向量
let IV:string = '' // 根据路由初始化

// 初始化密钥跟向量
function initKeyIv(path:string){
	path = path || "";
	const base64 : string = btoa(unescape(encodeURIComponent(path)));
	const sec: string = (base64 + base64 + base64).padEnd(40, 'k');
	AES_KEY = sec.substring(0, 16);
	IV  = sec.substring(12, 28);
}

//加密方法
export function encrypt( word:string ) {
	let key = CryptoJS.enc.Utf8.parse(AES_KEY)
	let iv = CryptoJS.enc.Utf8.parse(IV)
	let srcs = CryptoJS.enc.Utf8.parse(word)

	let encrypted = CryptoJS.AES.encrypt(srcs, key, {
		iv,
  		mode: CryptoJS.mode.CBC,
  		padding: CryptoJS.pad.Pkcs7
	});
	return encrypted.toString();
}

//解密方法
export function decrypt( word:string ,path:string) {
	initKeyIv(path);
	var key = CryptoJS.enc.Utf8.parse(AES_KEY)
	let iv = CryptoJS.enc.Utf8.parse(IV)
	
	var decrypt = CryptoJS.AES.decrypt(word, key, {
  		iv,
  		mode: CryptoJS.mode.CBC,
 		padding: CryptoJS.pad.Pkcs7
	})
	return decrypt.toString(CryptoJS.enc.Utf8).trim()
}

